package com.xiaogang.minio.service;

import cn.hutool.core.io.FileUtil;
import com.xiaogang.minio.model.FileMinioResult;
import com.xiaogang.minio.model.UploadParam;
import com.xiaogang.minio.utils.APIRs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @ProjectName : minio
 * @作者 : 侯小刚
 * @描述 :
 * @创建日期 : 2023/7/26 18:15
 */
@Service
public class MinioService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MinioUtils minioUtils;

    public final static String basePath = "C:\\Users\\Public\\Documents\\APPROVAI\\tmp";

    public APIRs uploadFileMinio(UploadParam param) {
        try {
            List<String> localPaths = param.getLocalPath();
            if(localPaths == null || localPaths.size() == 0) {
                return APIRs.fail("客户端文件路径不能为空");
            }
            List<FileMinioResult> resultList = new ArrayList<>();
            for (String localPath : localPaths) {
                if(!StringUtils.hasLength(localPath)) {
                    return APIRs.fail("客户端文件路径不能为空");
                }
                String[] tmps = localPath.split("tmp");
                if(tmps.length != 2) {
                    return APIRs.fail("客户端文件路径不正确");
                }
                String tmp = tmps[1];
                // 截取文件名
                String fileName = tmp.substring(tmp.lastIndexOf("/")+1);
                // 转一下文件夹路径 将/替换成\
                String tmpPath = tmp.replace("/","\\");
                // 拼接本地文件路径
                String localFilePath = basePath + File.separator + tmpPath;

                // 获取本地文件
                File file = new File(localFilePath);
                if(!file.exists()) {
                    return APIRs.fail("本地文件不存在");
                }
                // 将文件转成文件流
                InputStream inputStream = FileUtil.getInputStream(file);
                String filePath = minioUtils.fileUpload(inputStream, fileName);
                FileMinioResult build = FileMinioResult.builder().local(localPath).remote(filePath).size(file.length()).build();
                resultList.add(build);
            }
            return APIRs.success(resultList);
        }catch (Exception e){
            logger.error("上传文件到MINIO服务器失败",e);
            return APIRs.fail("上传文件到MINIO服务器失败");
        }
    }

}
